﻿using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows;

namespace YouTube
{
	public class TimeToDoubleConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if(targetType != typeof(double))
				return null;

			if(value is Duration)
			{
				Duration duration = (Duration)value;
				if(duration.HasTimeSpan)
					return duration.TimeSpan.TotalMilliseconds;
				else
					return 0;
			}
			else if(value is TimeSpan)
				return ((TimeSpan)value).TotalMilliseconds;
			else
				return null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if(!(value is double))
				return null;
			double d = (double)value;

			if(targetType == typeof(Duration))
			{
				if(d == 0)
					return new Duration();
				else
					return new Duration(TimeSpan.FromMilliseconds(d));
			}
			else if(targetType == typeof(TimeSpan))
				return TimeSpan.FromMilliseconds(d);
			else
				return null;
		}
	}
}
